package com.ukao.steward.ui.valetRunners.createOrder;


import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v7.widget.AppCompatCheckBox;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.ukao.steward.R;
import com.ukao.steward.base.MvpFragment;
import com.ukao.steward.bean.BalanceBean;
import com.ukao.steward.bean.OrderInfoBean;
import com.ukao.steward.bean.StringBean;
import com.ukao.steward.consts.Constant;
import com.ukao.steward.eventbus.PayEvent;
import com.ukao.steward.pesenter.valetRunners.OrderInfoPesenter;
import com.ukao.steward.ui.valetRunners.gathering.gatheringFragment;
import com.ukao.steward.ui.valetRunners.storage.StorageListFragment;
import com.ukao.steward.ui.valetRunners.waitingOrder.OrderdetailFragment;
import com.ukao.steward.util.CheckUtils;
import com.ukao.steward.util.L;
import com.ukao.steward.util.SpanUtils;
import com.ukao.steward.view.valetRunners.OrderInfoView;
import com.ukao.steward.widget.ZProgressHUD;

import org.greenrobot.eventbus.Subscribe;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

import static com.ukao.steward.R.id.balance_pay;
import static com.ukao.steward.R.id.check_balance_layout;
import static com.ukao.steward.R.id.coupons_layout;
import static com.ukao.steward.R.id.upay_layout;
import static com.ukao.steward.util.CheckUtils.isEmptyNumber;

/**
 * 订单信息
 */
public class PayOrderFragment extends MvpFragment<OrderInfoPesenter> implements OrderInfoView, DialogInterface.OnDismissListener {
    // TODO: Rename parameter arguments, choose names that match

    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    @BindView(R.id.back_btn)
    ImageView backBtn;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.title_layout)
    RelativeLayout titleLayout;

    Unbinder unbinder;
    @BindView(R.id.storge_go_btn)
    Button gatheringBtn;

    @BindView(R.id.enabled_checkBox)
    AppCompatCheckBox enabledCheckBox;
    @BindView(R.id.checkBox)
    CheckBox checkBox;
    @BindView(R.id.name_phone)
    TextView namePhone;
    @BindView(R.id.orderNo)
    TextView orderNo;
    @BindView(R.id.business)
    TextView business;
    @BindView(R.id.orderPrice)
    TextView orderPrice;
    @BindView(R.id.carriage)
    TextView carriage;
    @BindView(R.id.payablePrice)
    TextView payablePrice;
    @BindView(R.id.couponAmt)
    TextView couponAmt;
    @BindView(R.id.balance)
    TextView balance;
    @BindView(R.id.should_price)
    TextView shouldPrice;
    @BindView(R.id.pay_state)
    TextView payState;
    @BindView(R.id.look_detail)
    TextView lookDetail;
    @BindView(R.id.payRatio)
    TextView payRatio;
    @BindView(R.id.balance_usable_layout)
    FrameLayout balanceUsableLayout;
    @BindView(R.id.pay_image)
    ImageView payImage;


    @BindView(R.id.textView10)
    TextView textView10;
    @BindView(R.id.textView11)
    TextView textView11;
    @BindView(R.id.coupons_layout)
    LinearLayout couponsLayout;
    @BindView(R.id.balance_usable_tv)
    TextView balanceUsableTv;
    @BindView(balance_pay)
    TextView balancePay;
    @BindView(R.id.upay_card_tv)
    TextView upayCardTv;
    @BindView(R.id.upay_tv_balance)
    TextView upayTvBalance;
    @BindView(R.id.balance_two)
    TextView balanceTwo;
    @BindView(R.id.select_pay_mode)
    TextView selectPayMode;

    @BindView(R.id.pay_image_two)
    ImageView payImageTwo;
    @BindView(R.id.upay_layout)
    FrameLayout upayLayout;
    @BindView(R.id.pay_type_layout)
    LinearLayout payTypeLayout;
    @BindView(R.id.check_balance_layout)
    LinearLayout checkBalanceLayout;
    @BindView(R.id.line)
    View line;


    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    private String orderId;
    private boolean loadFinish = false;
    private OrderInfoBean mOrderInfoBean;
    private int totalBalance;
    private ZProgressHUD progressDialog;
    private Handler mHandler = new Handler();
    private String couponId; /*优惠券*/
    private OrderInfoBean.UPayCardBean uPayCard; /*优付卡*/
    private boolean isExistsCpnRel=false;

    public static PayOrderFragment newInstance(String orderId, OrderInfoBean mOrderInfoBean) {
        PayOrderFragment fragment = new PayOrderFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, orderId);
        args.putParcelable(ARG_PARAM2, mOrderInfoBean);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            orderId = getArguments().getString(ARG_PARAM1);
            mOrderInfoBean = getArguments().getParcelable(ARG_PARAM2);
        }
    }

    @Override
    protected OrderInfoPesenter createPresenter() {
        return new OrderInfoPesenter(this);
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_gathering, container, false);
        unbinder = ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView();
        initListener();
    }

    @Override
    protected void initView() {
        mOrderInfoBean.setOrderId(orderId);
        gatheringBtn.setText("收款");
        titleLayout.setBackgroundColor(getColors(R.color.colorPrimary));
        title.setText("收款");
        payState.setText(new SpanUtils().append("订单状态  ").append("未付款").setForegroundColor(getColors(R.color.red)).create());


    }

    @Override
    public void onSupportVisible() {
        super.onSupportVisible();

        if (!loadFinish)
            mvpPresenter.userExtbalance(mOrderInfoBean.getUserId());
    }

    @Override
    protected void initListener() {
        super.initListener();
        checkBox.setOnCheckedChangeListener(mOnCheckedListener);

    }

    CompoundButton.OnCheckedChangeListener mOnCheckedListener = new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (CheckUtils.isNull(mOrderInfoBean)) return;

            if (checkBox == buttonView&& checkBox.isEnabled()) {
                reckonShouldPice();


            }


        }
    };


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick({R.id.storge_go_btn, check_balance_layout, R.id.look_detail, R.id.back_btn, coupons_layout, R.id.balance_usable_layout, upay_layout})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.balance_usable_layout:

                setLeftBackStyle();


                break;
            case upay_layout:
                setRightBackStyle();

                break;


            case R.id.storge_go_btn:
                if (CheckUtils.isNull(mOrderInfoBean)) return;
                if (mOrderInfoBean.getShouldPrice() == 0) {
                    mvpPresenter.unlockOrder(mOrderInfoBean.getOrderId());

                } else {
                    start(gatheringFragment.newInstance(mOrderInfoBean, ""));
                }

                break;

            case check_balance_layout:
                if (CheckUtils.isNull(mOrderInfoBean)) {
                    return;
                }

                if (!checkBox.isChecked()) {
                    checkBox.setChecked(true);

                } else if (checkBox.isChecked()) {
                    checkBox.setChecked(false);
                }
                break;


            case R.id.look_detail:
                OrderdetailFragment  mOrderdetailFragment=OrderdetailFragment.createBuilder()
                        .orderId(orderId)
                        .build();
                start(mOrderdetailFragment);

                break;
            case R.id.back_btn:
                finish();
                break;

            case coupons_layout:
                startForResult(CouponFragment.newInstance(orderId, couponId), Constant.PAY_REQUEST_CODE);

                break;


        }
    }

    void setRightBackStyle() {
        if (payImageTwo.getVisibility() == View.VISIBLE) {
            payImageTwo.setVisibility(View.GONE);
            upayLayout.setBackgroundColor(getColors(R.color.white));
            reckonShouldPice();

        } else {
            if ( payImage.getVisibility() == View.VISIBLE){
                payImage.setVisibility(View.GONE);
                balanceUsableLayout.setBackgroundColor(getColors(R.color.white));
            }
            upayLayout.setBackgroundResource(R.drawable.shape_payorder_blue);
            payImageTwo.setVisibility(View.VISIBLE);
            uPayShouldPice();

        }
    }

    void setLeftBackStyle() {
        if (payImage.getVisibility() == View.VISIBLE) {
            payImage.setVisibility(View.GONE);
            balanceUsableLayout.setBackgroundColor(getColors(R.color.white));
            reckonShouldPice();


        } else {
            balanceUsableLayout.setBackgroundResource(R.drawable.shape_payorder_blue);
            payImage.setVisibility(View.VISIBLE);
            reckonShouldPice();
            if ( payImageTwo.getVisibility() == View.VISIBLE){
                payImageTwo.setVisibility(View.GONE);
                upayLayout.setBackgroundColor(getColors(R.color.white));
            }

        }
    }


    /**
     * 余额充足支付成功
     */
    @Override
    public void confirmPaySucceed() {
        if (mOrderInfoBean!=null&&mOrderInfoBean.isPayFinisEnterOrderDetails()) {

            if (findFragment(OrderdetailFragment.class)==null){
                popTo(StorageListFragment.class, true, () ->
                        start( OrderdetailFragment.createBuilder().orderId(mOrderInfoBean.getOrderId()).isPopToHome(true).build()));
            }else {
                popTo(OrderdetailFragment.class, true, () ->
                        start( OrderdetailFragment.createBuilder().orderId(mOrderInfoBean.getOrderId()).isPopToHome(false).build()));
            }

        }else{
            progressDialog = ZProgressHUD.getInstance(_mActivity);
            progressDialog.setOnDismissListener(this);
            progressDialog.showWithSuccess("支付成功");
            mHandler.postDelayed(() -> {
                progressDialog.dismiss();
                if (isAdded())
                    finish();
            }, 1000);

            payState.setText("已付款");
        }



    }

    /**
     * 填充订单信息
     *
     * @param mOrderInfoBean
     */

    @Override
    public void OrderInfoSucceed(OrderInfoBean mOrderInfoBean) {
        this.mOrderInfoBean = mOrderInfoBean;
        namePhone.setText(CheckUtils.isEmptyString(mOrderInfoBean.getName()) + "  " + CheckUtils.isEmptyString(mOrderInfoBean.getPhone()));
        orderNo.setText(CheckUtils.isEmptyString(mOrderInfoBean.getOrderNo()));/*订单*/
        /* mOrderInfoBean.getClototalAmount()*/
        orderPrice.setText("￥" +mOrderInfoBean.getOrderPrice());/*衣物总额*/
        carriage.setText("￥" + isEmptyNumber(mOrderInfoBean.getCarriage()));/*取送费*/
        payablePrice.setText("￥" + isEmptyNumber(mOrderInfoBean.getPayablePrice()));/*应收款*/
        isExistsCpnRel=CheckUtils.isEmpty(mOrderInfoBean.getCpnRelId());
        couponId = mOrderInfoBean.getCpnRelId();
        uPayCard = mOrderInfoBean.getUPayCard();
        balanceUsableTv.setText("余额￥" + CheckUtils.isEmptyNumber(totalBalance));
       /*余额不足的时候不可点击*/
        if (totalBalance == 0) {
            balanceUsableLayout.setEnabled(false);
            checkBalanceLayout.setEnabled(false);
            checkBox.setEnabled(false);
            checkBox.setButtonDrawable(R.drawable.pay_check_endle);

        }

        if (!CheckUtils.isNull(uPayCard)) {

            payRatio.setText("(支付比例 " + uPayCard.getPayRatio() + "%)");
            upayTvBalance.setText("余额￥" + CheckUtils.isEmptyNumber(uPayCard.getBalance()));
            /*判断是否可以选择优付*/
            upayLayout.setEnabled(uPayCard.getBalance() == 0 || uPayCard.getPayRatio()==0||!uPayCard.getIsEnable()?false:true);
        }else{
            upayLayout.setEnabled(false);
        }

        if (!CheckUtils.isNull(uPayCard)){
            line.setVisibility(View.GONE);
            selectPayMode.setVisibility(View.VISIBLE);
            payTypeLayout.setVisibility(View.VISIBLE);
            checkBalanceLayout.setVisibility(View.GONE);
        }else{
            selectPayMode.setVisibility(View.GONE);
            payTypeLayout.setVisibility(View.GONE);
        }
        if (totalBalance!=0&&!CheckUtils.isNull(uPayCard)){    /* 使用余额 */
            setLeftBackStyle();

        }else if (totalBalance!=0&&CheckUtils.isNull(uPayCard)){ /* 使用余额 */
            checkBox.setChecked(true);

        }else  if (totalBalance==0&&upayLayout.isEnabled()) {/* 使用U付卡余额 */
            setRightBackStyle();
        }else  if (totalBalance==0&&!upayLayout.isEnabled()) {
            reckonShouldPice();
        }



        Gson mGson = new Gson();
        if (!CheckUtils.isEmpty(mOrderInfoBean.getBusiness())) {  /*/*服务项目*/
            List<StringBean> mColorDesclist = mGson.fromJson(mOrderInfoBean.getBusiness(),
                    new TypeToken<List<StringBean>>() {
                    }.getType());
            StringBuffer mServeBuffer = new StringBuffer();
            for (int i = 0; i < mColorDesclist.size(); i++) {
                if (i != mColorDesclist.size() - 1) {
                    mServeBuffer.append(mColorDesclist.get(i).getName() + "/");
                } else {
                    mServeBuffer.append(mColorDesclist.get(i).getName());
                }


            }
            String strbusiness = mServeBuffer.toString();
            business.setText(strbusiness);

        }


    }

    /**
     * 计算优付收款
     */
    private void uPayShouldPice() {
        int couponAmt = mOrderInfoBean.getCouponAmt();
        mOrderInfoBean.setUseUPay(true);
        if (!CheckUtils.isNull(uPayCard) && !uPayCard.getUseCoupon()) {  /*是否可以使用优惠券*/
            couponAmt = 0;
        }
        setCouponAmt(couponAmt);
        int remainPrice = mOrderInfoBean.getPayablePrice() - couponAmt;  /*优惠后的金额*/
        int useBalance;
        int shouldPrices = 0;
        if (remainPrice > 0) {
            int mRatioPice = (remainPrice * uPayCard.getPayRatio()) / 100;  /*得到可支付比例金额*/
            int uPayPayPice = mRatioPice - uPayCard.getBalance();/*还应收款金额*/
            if (uPayPayPice > 0) {/*余额不足*/
                shouldPrices = remainPrice - uPayCard.getBalance();
                mOrderInfoBean.setShouldPrice(shouldPrices);
                useBalance = uPayCard.getBalance();
            } else {
                useBalance = mRatioPice;
                if (remainPrice - mRatioPice > 0) {/*应收款*/
                    shouldPrices = remainPrice - mRatioPice;
                } else {
                    shouldPrices = 0;
                }
            }

            balanceTwo.setText("抵扣" + CheckUtils.isEmptyNumber(useBalance));
            mOrderInfoBean.setShouldPrice(shouldPrices);

        }
        balancePay.setText("");
        shouldPrice.setText("￥" + CheckUtils.isEmptyNumber(shouldPrices));


    }

    /**
     * 设置优惠卷
     *
     * @param intCouponAmt
     */
    private void setCouponAmt(int intCouponAmt) {
        couponsLayout.setEnabled(true);
        if (intCouponAmt != 0) {/*优惠券*/
            couponAmt.setText("-" + isEmptyNumber(intCouponAmt));
            couponAmt.setTextColor(getColors(R.color.pink_pice));
            couponAmt.setTextSize(15);

        } else {
            couponAmt.setTextColor(getColors(R.color.glay));
            if (!CheckUtils.isNull(uPayCard) && !uPayCard.getUseCoupon() && mOrderInfoBean.isUseUPay()) {
                couponsLayout.setEnabled(false);
                couponAmt.setText("不能与优付卡同时使用");
                couponAmt.setTextSize(14);
            } else if (isExistsCpnRel){
                couponAmt.setTextSize(14);
                couponAmt.setText("无可用");
            }else{
                couponAmt.setTextSize(14);
                couponAmt.setText("");
            }


        }
    }


    /**
     * 计算应收款  支付金额    优惠券  余额
     */
    private void reckonShouldPice() {
        if (!CheckUtils.isNull(uPayCard)) {
            mOrderInfoBean.setUseUPay(false);
        }
        setCouponAmt(mOrderInfoBean.getCouponAmt());/*设置优惠卷*/
        if (checkBox.isChecked()||payImage.getVisibility()==View.VISIBLE) {
            int remainPrice = mOrderInfoBean.getPayablePrice() - mOrderInfoBean.getCouponAmt();/*应收款*/
            int useBalance;
            if (totalBalance - remainPrice < 0) { /*总余额 扣去优惠后的金额*/
                useBalance = mOrderInfoBean.getBalance();
            } else {
                useBalance = remainPrice;

            }
            mOrderInfoBean.setUseBalance(useBalance);
            mOrderInfoBean.setEnableBalance(true);
            int shouldPayPrice = mOrderInfoBean.getPayablePrice() - useBalance - mOrderInfoBean.getCouponAmt();
            mOrderInfoBean.setShouldPrice(shouldPayPrice);

            shouldPrice.setText("￥" + isEmptyNumber(mOrderInfoBean.getShouldPrice()));
            balancePay.setText(useBalance > 0 ? "抵扣" + isEmptyNumber(useBalance) : "");
            balanceTwo.setText("");
            balance.setText(useBalance > 0 ? "-" + isEmptyNumber(useBalance) : "");/*余额*/
            balance.setTextColor(getColors(R.color.pink_pice));
        } else {
            balancePay.setText("");
            balanceTwo.setText("");
            mOrderInfoBean.setUseBalance(0);
            mOrderInfoBean.setEnableBalance(false);
            int remainPrice = mOrderInfoBean.getPayablePrice() - mOrderInfoBean.getCouponAmt();/*应收款*/
            mOrderInfoBean.setShouldPrice(remainPrice);
            shouldPrice.setText(remainPrice >= 0 ? "￥" + isEmptyNumber(remainPrice) : "￥0.00");
            String   strbalance="余额￥" + isEmptyNumber(totalBalance);
            balance.setText(strbalance);/*余额*/
            balance.setTextColor(getColors(R.color.glay));

        }
    }


    /**
     * 用户余额
     *
     * @param mBalanceBean
     */
    @Override
    public void useBalanceData(BalanceBean mBalanceBean) {
        loadFinish = true;
        totalBalance = mBalanceBean.getBalance();
        OrderInfoSucceed(mOrderInfoBean);
    }

    @Override
    public void unlockOrderData() {
        mvpPresenter.confirmPay(mOrderInfoBean.getOrderId(), mOrderInfoBean.getUseBalance(), mOrderInfoBean.isUseUPay(), mOrderInfoBean.getCpnRelId());
    }

    @Override

    protected boolean useEventBus() {
        return true;
    }


    @Override
    public void onDismiss(DialogInterface dialog) {
        PayEvent.postHasData(PayEvent.Message.PAY_FINISG, mOrderInfoBean);


    }

    @Subscribe
    public void onEvent(PayEvent event) {
        switch (event.getMessage()) {
            case PAY_FINISG:
                if (progressDialog == null) {
                    finish();
                }

                break;

        }
    }


    @Override
    public void onFragmentResult(int requestCode, int resultCode, Bundle data) {
        super.onFragmentResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case Constant.PAY_REQUEST_CODE: /*使用优惠券*/
                    if (mOrderInfoBean==null)return;
                    mOrderInfoBean.setCouponAmt(data.getInt(ARG_PARAM1));
                    couponId = data.getString(ARG_PARAM2);
                    mOrderInfoBean.setCpnRelId(couponId);
                    L.i("couponId=" + couponId);
                    if (payImageTwo.getVisibility()==View.VISIBLE) {
                        uPayShouldPice();
                    } else {
                        reckonShouldPice();
                    }

                    break;

            }


        }
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        mHandler.removeCallbacksAndMessages(null);
    }
}

